"""
AI-SOES - 人工智能集成模块
包含AI服务和智能分析相关功能
"""
from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.db.models import Count, Avg
from decimal import Decimal

from apps.core.models import TimeStampedModel

User = get_user_model()


class AIServiceConfig(TimeStampedModel):
    """
    AI服务配置
    管理各种AI服务的配置参数
    """
    SERVICE_CHOICES = [
        ('openai_gpt', 'OpenAI GPT'),
        ('azure_openai', 'Azure OpenAI'),
        ('baidu_ernie', '百度文心'),
        ('ali_tongyi', '阿里通义'),
        ('tencent_hunyuan', '腾讯混元'),
        ('local_llm', '本地大模型'),
    ]

    name = models.CharField('配置名称', max_length=100)
    service_type = models.CharField('服务类型', max_length=50, choices=SERVICE_CHOICES)
    api_key = models.CharField('API密钥', max_length=500, blank=True)
    api_url = models.URLField('API地址', blank=True)
    model_name = models.CharField('模型名称', max_length=100, blank=True)

    # 配置参数 (JSON格式)
    config_params = models.JSONField('配置参数', default=dict, blank=True)

    # 状态
    is_active = models.BooleanField('是否启用', default=False)
    is_primary = models.BooleanField('主要配置', default=False)

    # 使用限制
    rate_limit = models.IntegerField('每分钟限制', default=60, help_text='每分钟请求次数')
    daily_limit = models.IntegerField('每日限制', default=1000, help_text='每日请求次数')

    # 使用统计
    daily_usage = models.IntegerField('今日使用次数', default=0)
    last_used = models.DateTimeField('最后使用', null=True, blank=True)

    class Meta:
        db_table = 'ai_service_configs'
        verbose_name = 'AI服务配置'
        verbose_name_plural = 'AI服务配置'
        ordering = ['-is_primary', '-is_active', 'name']
        unique_together = [['service_type', 'model_name']]

    def __str__(self):
        return f"{self.name} ({self.service_type})"

    def can_use(self):
        """检查是否可以使用该服务"""
        if not self.is_active:
            return False

        # 检查每日限制
        today = timezone.now().date()
        if self.last_used and self.last_used.date() == today:
            return self.daily_usage < self.daily_limit

        return True

    def record_usage(self):
        """记录使用"""
        self.daily_usage += 1
        self.last_used = timezone.now()
        self.save(update_fields=['daily_usage', 'last_used'])

    def reset_daily_usage(self):
        """重置每日使用次数"""
        self.daily_usage = 0
        self.save(update_fields=['daily_usage'])


class AIRequestLog(TimeStampedModel):
    """
    AI请求日志
    记录所有AI服务的调用
    """
    REQUEST_TYPES = [
        ('question_generation', '题目生成'),
        ('question_analysis', '题目分析'),
        ('auto_grading', '自动评分'),
        ('difficulty_adjustment', '难度调整'),
        ('plagiarism_check', '抄袭检测'),
        ('content_analysis', '内容分析'),
        ('smart_recommendation', '智能推荐'),
        ('learning_analysis', '学习分析'),
    ]

    STATUS_CHOICES = [
        ('pending', '处理中'),
        ('success', '成功'),
        ('failed', '失败'),
        ('timeout', '超时'),
    ]

    request_type = models.CharField('请求类型', max_length=50, choices=REQUEST_TYPES)
    service_config = models.ForeignKey(
        AIServiceConfig,
        on_delete=models.SET_NULL,
        related_name='request_logs',
        verbose_name='使用AI服务',
        null=True
    )

    # 请求用户
    user = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        related_name='ai_requests',
        verbose_name='请求用户',
        null=True
    )

    # 请求内容
    input_data = models.JSONField('输入数据', default=dict)
    output_data = models.JSONField('输出数据', default=dict, blank=True)

    # 状态信息
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='pending')
    error_message = models.TextField('错误信息', blank=True)

    # 性能指标
    response_time = models.FloatField('响应时间(秒)', null=True, blank=True)
    token_count = models.IntegerField('Token数量', null=True, blank=True)
    cost = models.DecimalField('费用', max_digits=10, decimal_places=6, null=True, blank=True)

    class Meta:
        db_table = 'ai_request_logs'
        verbose_name = 'AI请求日志'
        verbose_name_plural = 'AI请求日志'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['request_type', 'status']),
            models.Index(fields=['user']),
            models.Index(fields=['created_at']),
            models.Index(fields=['service_config']),
        ]

    def __str__(self):
        return f"{self.get_request_type_display()} - {self.status}"


class AIQuestionGeneration(TimeStampedModel):
    """
    AI题目生成记录
    记录AI生成的题目和结果
    """
    GENERATION_TYPES = [
        ('auto', '自动生成'),
        ('template_based', '基于模板'),
        ('knowledge_point', '基于知识点'),
        ('difficulty_based', '基于难度'),
        ('style_based', '基于风格'),
    ]

    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='ai_generated_questions',
        verbose_name='创建者'
    )

    # 生成参数
    generation_type = models.CharField('生成类型', max_length=50, choices=GENERATION_TYPES)
    knowledge_points = models.JSONField('知识点', default=list, blank=True)
    difficulty = models.CharField('难度', max_length=20, blank=True)
    question_type = models.CharField('题目类型', max_length=50, blank=True)
    count = models.IntegerField('生成数量', default=1)

    # 生成结果
    generated_questions = models.JSONField('生成题目', default=list)
    accepted_questions = models.JSONField('采纳题目', default=list, blank=True)

    # 质量评估
    quality_score = models.DecimalField('质量分数', max_digits=3, decimal_places=2, null=True, blank=True)
    review_status = models.CharField(
        '审核状态',
        max_length=20,
        choices=[
            ('pending', '待审核'),
            ('approved', '已通过'),
            ('rejected', '已拒绝'),
        ],
        default='pending'
    )

    # AI请求关联
    ai_request_log = models.OneToOneField(
        AIRequestLog,
        on_delete=models.SET_NULL,
        related_name='question_generation',
        verbose_name='AI请求记录',
        null=True
    )

    class Meta:
        db_table = 'ai_question_generation'
        verbose_name = 'AI题目生成记录'
        verbose_name_plural = 'AI题目生成记录'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.real_name} - {self.get_generation_type_display()} ({self.count}题)"


class AIAutoGrading(TimeStampedModel):
    """
    AI自动评分记录
    记录AI评分的结果和过程
    """
    GRADING_TYPES = [
        ('subjective', '主观题'),
        ('essay', '作文'),
        ('programming', '编程题'),
        ('image_analysis', '图片分析'),
        ('text_similarity', '文本相似度'),
    ]

    # 关联考试答案
    examination_answer = models.OneToOneField(
        'examination.ExaminationAnswer',
        on_delete=models.CASCADE,
        related_name='ai_grading',
        verbose_name='考试答案'
    )

    # 评分配置
    grading_type = models.CharField('评分类型', max_length=50, choices=GRADING_TYPES)
    max_score = models.DecimalField('满分', max_digits=6, decimal_places=2)

    # AI评分结果
    ai_score = models.DecimalField('AI得分', max_digits=6, decimal_places=2, null=True, blank=True)
    confidence = models.DecimalField('置信度', max_digits=3, decimal_places=2, null=True, blank=True)

    # 详细评分信息
    scoring_details = models.JSONField('评分详情', default=dict, blank=True)
    rubric_results = models.JSONField('评分标准结果', default=dict, blank=True)

    # 反馈信息
    feedback = models.TextField('AI反馈', blank=True)
    improvement_suggestions = models.TextField('改进建议', blank=True)

    # 人工审核
    human_reviewer = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        related_name='reviewed_ai_gradings',
        verbose_name='人工审核员',
        null=True
    )
    final_score = models.DecimalField('最终得分', max_digits=6, decimal_places=2, null=True, blank=True)
    is_approved = models.BooleanField('是否审核通过', default=False)

    # AI请求关联
    ai_request_log = models.OneToOneField(
        AIRequestLog,
        on_delete=models.SET_NULL,
        related_name='auto_grading',
        verbose_name='AI请求记录',
        null=True
    )

    class Meta:
        db_table = 'ai_auto_grading'
        verbose_name = 'AI自动评分记录'
        verbose_name_plural = 'AI自动评分记录'
        ordering = ['-created_at']

    def __str__(self):
        return f"AI评分 - {self.examination_answer}"


class AIAnalysis(TimeStampedModel):
    """
    AI分析记录
    记录各类AI分析的结果
    """
    ANALYSIS_TYPES = [
        ('exam_difficulty', '考试难度分析'),
        ('question_quality', '题目质量分析'),
        ('student_performance', '学生表现分析'),
        ('learning_path', '学习路径分析'),
        ('knowledge_gap', '知识点差距分析'),
        ('plagiarism', '抄袭检测'),
        ('content_quality', '内容质量分析'),
    ]

    analysis_type = models.CharField('分析类型', max_length=50, choices=ANALYSIS_TYPES)
    target_object_type = models.CharField('目标对象类型', max_length=50)  # 'exam', 'question', 'user', etc.
    target_object_id = models.PositiveIntegerField('目标对象ID')

    # 分析参数
    analysis_params = models.JSONField('分析参数', default=dict)

    # 分析结果
    analysis_results = models.JSONField('分析结果', default=dict)
    insights = models.JSONField('洞察发现', default=dict, blank=True)
    recommendations = models.JSONField('建议', default=dict, blank=True)

    # 质量指标
    confidence_level = models.DecimalField('置信度等级', max_digits=3, decimal_places=2, null=True, blank=True)
    completeness = models.DecimalField('完整度', max_digits=3, decimal_places=2, null=True, blank=True)

    # 状态信息
    status = models.CharField(
        '状态',
        max_length=20,
        choices=[
            ('pending', '待处理'),
            ('processing', '处理中'),
            ('completed', '已完成'),
            ('failed', '失败'),
        ],
        default='pending'
    )

    # AI请求关联
    ai_request_log = models.OneToOneField(
        AIRequestLog,
        on_delete=models.SET_NULL,
        related_name='analysis',
        verbose_name='AI请求记录',
        null=True
    )

    class Meta:
        db_table = 'ai_analysis'
        verbose_name = 'AI分析记录'
        verbose_name_plural = 'AI分析记录'
        ordering = ['-created_at']
        unique_together = [['analysis_type', 'target_object_type', 'target_object_id']]
        indexes = [
            models.Index(fields=['analysis_type', 'status']),
            models.Index(fields=['target_object_type', 'target_object_id']),
        ]

    def __str__(self):
        return f"{self.get_analysis_type_display()} - {self.target_object_type}:{self.target_object_id}"


class AIRecommendation(TimeStampedModel):
    """
    AI推荐记录
    记录智能推荐的结果
    """
    RECOMMENDATION_TYPES = [
        ('question_practice', '题目练习推荐'),
        ('study_material', '学习资料推荐'),
        ('learning_path', '学习路径推荐'),
        ('exam_preparation', '考试准备推荐'),
        ('weakness_improvement', '薄弱环节推荐'),
    ]

    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='ai_recommendations',
        verbose_name='目标用户'
    )

    recommendation_type = models.CharField('推荐类型', max_length=50, choices=RECOMMENDATION_TYPES)

    # 推荐内容
    recommendations = models.JSONField('推荐内容', default=list)
    reasoning = models.JSONField('推荐理由', default=dict)

    # 推荐质量
    relevance_score = models.DecimalField('相关度分数', max_digits=3, decimal_places=2, null=True, blank=True)
    diversity_score = models.DecimalField('多样性分数', max_digits=3, decimal_places=2, null=True, blank=True)

    # 用户反馈
    user_feedback = models.JSONField('用户反馈', default=dict, blank=True)
    is_helpful = models.BooleanField('是否有帮助', null=True, blank=True)
    feedback_notes = models.TextField('反馈备注', blank=True)

    # 有效期
    valid_until = models.DateTimeField('有效期至', null=True, blank=True)
    is_active = models.BooleanField('是否有效', default=True)

    class Meta:
        db_table = 'ai_recommendations'
        verbose_name = 'AI推荐记录'
        verbose_name_plural = 'AI推荐记录'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'recommendation_type']),
            models.Index(fields=['valid_until', 'is_active']),
        ]

    def __str__(self):
        return f"{self.user.real_name} - {self.get_recommendation_type_display()}"

    def is_expired(self):
        """检查推荐是否过期"""
        if not self.valid_until:
            return False
        return timezone.now() > self.valid_until